package com.aaron.sqlsession.impl;

import com.aaron.config.Configuration;
import com.aaron.sqlsession.Executor;
import com.aaron.sqlsession.SqlSession;

import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

/**
 * @Description
 * @Author Aaron
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2021/10/30
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    private Executor executor = new DefaultExecutor();

    @Override
    public <E> List<E> selectAll(String statementId,Object... params) throws Exception {
        List<E> query = executor.query(configuration, configuration.getMappers().get(statementId), params);
        return query;
    }

    @Override
    public <T> T selectByCondition(String statementId, Object... params) throws Exception {
        List<Object> list = selectAll(statementId,params);
        if (list.size() == 1) {
            return (T) list.get(0);
        } else {
            throw new RuntimeException("返回结果过多");
        }
    }

    @Override
    public void close() throws SQLException {

    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(),
                new Class[]{mapperClass},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        String methodName = method.getName();
                        String className = method.getDeclaringClass().getName();
                        String statement = className+"."+methodName;
                        Type genericReturnType = method.getGenericReturnType();
                        if (genericReturnType instanceof ParameterizedType) {
                            return selectAll(statement, args);
                        }
                        return selectByCondition(statement, args);
                    }
                });
        return (T) proxyInstance;
    }
}
